home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 452 < prev    next >
Encoding:
Internet Message Format  |  1996-08-05  |  2.2 KB

  1. Path: oxy.rust.net!usenet
  2. From: pgunn@mail.cbf.com (Paul Gunn)
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: Constructor Exceptions
  5. Date: Thu, 04 Jan 1996 17:03:00 GMT
  6. Organization: Rust Net - High Speed Internet in Detroit  810-642-2276
  7. Message-ID: <4ch1c3$bsm@oxy.rust.net>
  8. References: <4bud9g$pv5@oxy.rust.net> <4cbhcl$kst@dawn.mmm.com> <4ce68n$8u4@sundog.tiac.net>
  9. NNTP-Posting-Host: pgunn.cbf.com
  10. X-Newsreader: Forte Agent .99c/32.126
  11.  
  12. page@tiac.net (Chris Page) wrote:
  13.  
  14.  
  15. >:> I use Microsoft Visual C++, and have been gradually making use of
  16. >:> exceptions in my code. I'm interested in using exceptions in my
  17. >:> constructor code, but according to a MS article, when an exception is
  18. >:> thrown from a constructor on a heap object, the memory will not be
  19. >:> freed.
  20. >
  21. >:> Is this behavior parculiar to the Microsoft implementation or is it
  22. >:> generally the case?
  23. >
  24. >:It is not generally the case.  Compilers that adhere to the standard
  25. >:will produce code that does not leak memory in this way.
  26. >
  27. >Sure, they'll clean up 'this', but the programmer is responsible for
  28. >any and all heap memory allocated within the body of constructor.
  29.  
  30. Here is an excerpt from the Visual C++ 2.1 documentation. It seems to
  31. indicate that 'this' will not be cleaned up.
  32.  
  33. >
  34. Throwing an exception in a constructor is tricky, however, because the
  35. memory for the object itself has already been allocated by the time
  36. the constructor is called. There is no simple way to deallocate the
  37. memory occupied by the object from within the constructor for that
  38. object. Thus, you will find that throwing an exception in a
  39. constructor will result in the object remaining allocated. For a
  40. discussion of how to detect objects in your program that have not been
  41. deallocated, see the article Diagnostics: Detecting Memory Leaks. 
  42. If you are performing operations in your constructor that can fail, it
  43. might be a better idea to put those operations into a separate
  44. initialization function rather than throwing an exception in the
  45. constructor. That way, you can safely construct the object and get a
  46. valid pointer to it. Then, you can call the initialization function
  47. for the object. If the initialization function fails, you can delete
  48. the object directly. 
  49. <
  50.  
  51. What do you think?
  52.  
  53.  
  54.  
  55.